package alibaba.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SignatureUtils {

    private static final String HASH_ALGORITHM = "SHA-256";
    private static final int BUFFER_SIZE = 2048;
    public static final int SHA_256_SIGNATURE_SIZE = 32;
    public static final byte[] EMPTY_SIGNATURE = new byte[SHA_256_SIGNATURE_SIZE];
    
    public static byte[] sign(String fileName) throws IOException {
        
        MessageDigest hash = null;
        
        File file = new File(fileName);
        if (!file.isFile()) {
            throw new FileNotFoundException(fileName);
        }
        if (!file.canRead()) {
            throw new IOException(fileName + " is not accessible");
        }
        
        try {
            hash = MessageDigest.getInstance(HASH_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            // this cannot happen
        }
        
        hash.reset();
        
        FileInputStream inputStream = new FileInputStream(file);
        
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = 0;
        
        while((bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
            hash.update(buffer, 0, bytesRead);
        }
        
        inputStream.close();
        
        return hash.digest();
        
    }
    
}
